//    Openbravo POS is a point of sales application designed for touch screens.
//    Copyright (C) 2007-2009 Openbravo, S.L.
//    http://www.openbravo.com/product/pos
//
//    This file is part of Openbravo POS.
//
//    Openbravo POS is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    Openbravo POS is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with Openbravo POS.  If not, see <http://www.gnu.org/licenses/>.

package com.openbravo.pos.forms;

import cn.ekuma.epos.businesslogic.RoleUtil;
import cn.ekuma.epos.datalogic.I_DataLogicCustomers;
import cn.ekuma.epos.datalogic.I_DataLogicSystem;
import cn.ekuma.security.I_SecurityManager;
import com.openbravo.bean.AppUser;
import com.openbravo.pos.base.AppConfig;
import com.openbravo.pos.base.BeanFactoryException;
import com.openbravo.pos.base.AppLocal;
import com.openbravo.data.basic.BasicException;
import java.awt.*;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.openbravo.data.gui.MessageInf;
import com.openbravo.data.gui.JMessageDialog;
import com.openbravo.pos.model.BaseSwingModel;
import com.openbravo.pos.scripting.ScriptException;
import com.openbravo.pos.util.Hashcypher;

//import com.l2fprod.common.swing.JTaskPane;
//import com.l2fprod.common.swing.JTaskPaneGroup;
import com.openbravo.pos.util.StringUtils;

/**
 *
 * @author adrianromero
 */
public class JPrincipalApp extends AbstratJPrincipalApp {

    private static Logger logger = Logger.getLogger("com.openbravo.pos.forms.JPrincipalApp");
    
    private JRootApp m_appview;
    private AppUser m_appuser;
    

	private I_DataLogicCustomers m_dlCustomer;
	private I_DataLogicSystem m_dlSystem;
	BaseSwingModel swingModel;

	private I_SecurityManager security;

	
    /** Creates new form JPrincipalApp */
    public JPrincipalApp(JRootApp appview, AppUser appuser,BaseSwingModel swingModel) {
        super(appview,appuser);
        m_appview = appview; 
        m_appuser = appuser;
                   
        this.m_dlSystem = swingModel.getDLSystem();
        this.m_dlCustomer=swingModel.getDLCustomer();
        this.swingModel=swingModel;
        security=swingModel.getModelSecurityManager();
      
        
        // Cargamos los permisos del usuario
        //RoleUtil.fillPermissions(appuser, m_dlSystem);
        //AppConfig.setAppProperty(AppConfig.SHOW_BUY_PRICE, RoleUtil.hasPermission(m_appuser,RoleUtil.Permission_SHOW_BUY_PRICE)==true?"true":"false");
        AppConfig.setAppProperty(AppConfig.SHOW_BUY_PRICE, security.hasPermissionByName(RoleUtil.Permission_SHOW_BUY_PRICE)==true?"true":"false");

       try {
           String menuModel=System.getProperty(AppLocal.APP_MenuModelPropName, AppLocal.APP_DefaultMenuModel);
           String menuText=null;
           if(!AppLocal.APP_MenuModel_POS.equalsIgnoreCase(menuModel)){
                RoleUtil.fillOrderTypePermission(appuser, m_dlSystem);
                RoleUtil.fillUserStateProcessPermission(appuser, m_dlSystem);
                menuText=m_dlSystem.getResourceAsText(menuModel+"."+appuser.getName());
                appview.showCommandInput();
           }
           if(menuText==null||menuText.isEmpty())
               menuText=m_dlSystem.getResourceAsText(menuModel);
           m_jPanelLeft.setViewportView(getScriptMenu(menuText));
        } catch (ScriptException e) {
            logger.log(Level.SEVERE, "Cannot read Menu.Root resource. Trying defaut menu.", e);
            try {
                m_jPanelLeft.setViewportView(getScriptMenu(StringUtils.readResource("/com/openbravo/pos/templates/Menu.Root.txt")));
            } catch (IOException ex) {
                logger.log(Level.SEVERE, "Cannot read default menu", ex);
            } catch (ScriptException es) {
                logger.log(Level.SEVERE, "Cannot read default menu", es);
            }
        }
    }

    
    public void activate() {
        
        if(getUser().getRole().equalsIgnoreCase("0")||getUser().getRole().equalsIgnoreCase("1"))
              setMenuVisible(true); 
        else
              setMenuVisible(false);
        
        // arranco la primera opcion
        if (m_actionfirst != null) {
            m_actionfirst.actionPerformed(null);
            m_actionfirst = null;
        }
    }
    
    public boolean deactivate() {
        if (m_jLastView == null) {
            return true;
        } else if (m_jLastView.deactivate()) {
            m_jLastView = null;
            showView("<NULL>");       
            return true;
        } else {
            return false;
        }
        
    }
    
    
    private void showView(String sView) {
        CardLayout cl = (CardLayout)(m_jPanelContainer.getLayout());
        cl.show(m_jPanelContainer, sView);       
    }
    
    public AppUser getUser() {
        return m_appuser;
    }
    
  
     public void showTaskAdmin(String sTaskClass){
    	m_appview.waitCursorBegin();
    	 JPanelView m_jMyView = (JPanelView) m_aCreatedViews.get(sTaskClass);

         // cierro la antigua
         if (m_jLastView == null || (m_jMyView != m_jLastView && m_jLastView.deactivate())) {

             // Construct the new view
             if (m_jMyView == null) {

                 // Is the view prepared
                 m_jMyView = m_aPreparedViews.get(sTaskClass);
                 if (m_jMyView == null) {
                     // The view is not prepared. Try to get as a Bean...
                     try {
                         m_jMyView = (JPanelView) swingModel.getBean(sTaskClass);
                     } catch (BeanFactoryException e) {
                         m_jMyView = new JPanelNull(m_appview, e);
                     }
                 }

                 m_jMyView.getComponent().applyComponentOrientation(getComponentOrientation());
                 m_jPanelContainer.add(m_jMyView.getComponent(), sTaskClass);
                 m_aCreatedViews.put(sTaskClass, m_jMyView);
             }

             // ejecuto la tarea
             try {
                 m_jMyView.activate();
             } catch (BasicException e) {
                 JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notactive"), e));
             }

             // se tiene que mostrar el panel
             m_jLastView = m_jMyView;
            if(getUser().getRole().equalsIgnoreCase("0")||getUser().getRole().equalsIgnoreCase("1"))
                setMenuVisible(true);
                //setMenuVisible(getBounds().width > 800);
            else
                setMenuVisible(false);

             showView(sTaskClass);
             // Y ahora que he cerrado la antigua me abro yo
             String sTitle = m_jMyView.getTitle();
             m_jPanelTitle.setVisible(sTitle != null);
             m_jTitle.setText(sTitle);
         }
         m_appview.waitCursorEnd();
    }
    
    
    public void showTask(String sTaskClass) {

        if (security.hasPermissionByName(sTaskClass)) {
        	showTaskAdmin(sTaskClass);
        } else  {
            // No hay permisos para ejecutar la accion...
            JMessageDialog.showMessage(this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notpermissions")));
        }
       
    }

    public void executeTask(String sTaskClass) {

        m_appview.waitCursorBegin();

        if (security.hasPermissionByName(sTaskClass)) {
            try {
                ProcessAction myProcess = (ProcessAction) swingModel.getBean(sTaskClass);

                // execute the proces
                try {
                    MessageInf m = myProcess.execute();
                    if (m != null) {
                        // si devuelve un mensaje, lo muestro
                        JMessageDialog.showMessage(JPrincipalApp.this, m);
                    }
                } catch (BasicException eb) {
                    // Si se produce un error lo muestro.
                    JMessageDialog.showMessage(JPrincipalApp.this, new MessageInf(eb));
                }
            } catch (BeanFactoryException e) {
                JMessageDialog.showMessage(JPrincipalApp.this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("Label.LoadError"), e));
            }
        } else  {
            // No hay permisos para ejecutar la accion...
            JMessageDialog.showMessage(JPrincipalApp.this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.notpermissions")));
        }
        m_appview.waitCursorEnd();
    }

	@Override
	public String getHostName() {
		return m_appview.getProperties().getHost();
	}
	


	@Override
	public
	void changePassword() {
		String sNewPassword;
    	if(m_appview.isCustomerView()){
    		sNewPassword = Hashcypher.changePassword(JPrincipalApp.this, null);
    		if (sNewPassword != null) {
                try {
                	m_dlCustomer.execChangePassword(m_appview.getCustomerInfo().getId(),sNewPassword);
                } catch (BasicException e) {
                    JMessageDialog.showMessage(JPrincipalApp.this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotchangepassword")));             
                }
              }
    	}else{
          sNewPassword = Hashcypher.changePassword(JPrincipalApp.this, m_appuser.getPassword());
          if (sNewPassword != null) {
            try {
                m_dlSystem.execChangePassword(m_appuser.getId(),sNewPassword);
                m_appuser.setPassword(sNewPassword);
            } catch (BasicException e) {
                JMessageDialog.showMessage(JPrincipalApp.this, new MessageInf(MessageInf.SGN_WARNING, AppLocal.getIntString("message.cannotchangepassword")));             
            }
          }
    	}
		
	}

	@Override
	public
	void lockScreen() {
		String sNewPassword;
    	if(!m_appview.isCustomerView()){
           Hashcypher.checkPassword(JPrincipalApp.this, m_appuser.getPassword());
    	}
	}


	@Override
	public
	boolean isAdminLogin() {
		return getUser().getId().equalsIgnoreCase("0");
	}
}
